package com.my.algorithmlearning.leetcode;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName Medium_49_GroupAnagrams
 * @Description 题目链接：https://leetcode.cn/problems/group-anagrams/?favorite=2cktkvj
 * 一句话解题思路：互为异位词所包含的字符是一样的
 * 题解：https://leetcode.cn/problems/group-anagrams/solution/zhong-deng-49-zi-mu-yi-wei-ci-fen-zu-zhu-if7u/
 * @Author wanghaiwei
 * @Date 2023/2/28 10:50
 */
public class Medium_49_GroupAnagrams {
    public List<List<String>> groupAnagrams(String[] strs) {
        if (strs == null || strs.length == 0) {
            return new ArrayList<>();
        }
        Map<String, List<String>> maskWithStrs = new HashMap<>();
        for (String s : strs) {
            int[] countForChars = new int[26];
            for (int cIdx = 0; cIdx < s.length(); cIdx++) {
                countForChars[s.charAt(cIdx) - 'a']++;
            }
            String mask = Arrays.stream(countForChars).mapToObj(String::valueOf).collect(Collectors.joining("&"));
            maskWithStrs.computeIfAbsent(mask, k -> new ArrayList<>()).add(s);
        }
        return new ArrayList<>(maskWithStrs.values());
    }

    public static void main(String[] args) {
        Medium_49_GroupAnagrams solution = new Medium_49_GroupAnagrams();
        List<List<String>> resultLs = solution.groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"});
        Assert.isTrue(resultLs.size() == 3, "[\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"]计算错误，预期[[\"bat\"],[\"nat\",\"tan\"],[\"ate\",\"eat\",\"tea\"]]， 实际：");
        System.out.println(resultLs.stream().map(r -> "[" + StringUtils.join(r, ",") + "]").collect(Collectors.joining(",")));

        resultLs = solution.groupAnagrams(new String[]{""});
        Assert.isTrue(resultLs.size() == 1, "[\"\"]计算错误，预期[[\"\"]]， 实际：");
        System.out.println(resultLs.stream().map(r -> "[" + StringUtils.join(r, ",") + "]").collect(Collectors.joining(",")));

        resultLs = solution.groupAnagrams(new String[]{"a"});
        Assert.isTrue(resultLs.size() == 1, "[\"a\"]计算错误，预期[[\"a\"]]， 实际：");
        System.out.println(resultLs.stream().map(r -> "[" + StringUtils.join(r, ",") + "]").collect(Collectors.joining(",")));

        resultLs = solution.groupAnagrams(new String[]{"ddddddddddg", "dgggggggggg"});
        Assert.isTrue(resultLs.size() == 2, "[\"ddddddddddg\",\"dgggggggggg\"]计算错误，预期[[\"dgggggggggg\"],[\"ddddddddddg\"]]， 实际：");
        System.out.println(resultLs.stream().map(r -> "[" + StringUtils.join(r, ",") + "]").collect(Collectors.joining(",")));

        resultLs = solution.groupAnagrams(new String[]{"bdddddddddd", "bbbbbbbbbbc"});
        Assert.isTrue(resultLs.size() == 2, "[\"bdddddddddd\",\"bbbbbbbbbbc\"]计算错误，预期[[\"bbbbbbbbbbc\"],[\"bdddddddddd\"]]， 实际：");
        System.out.println(resultLs.stream().map(r -> "[" + StringUtils.join(r, ",") + "]").collect(Collectors.joining(",")));
    }
}
